package com.weike.wk_android.interceptor;

import android.text.TextUtils;

import com.weike.wk_android.commons.Constants;
import com.weike.wk_android.utils.Utils;

import java.io.IOException;

import okhttp3.CacheControl;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

public class CacheInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
        // 获取request拦截对象
        Request request = chain.request();
        // 判断有无网络连接
        if (!Utils.isConnectByNet()) {
            // 如果没有网络，从缓存获取数据
            request = request.newBuilder()
                    .cacheControl(CacheControl.FORCE_CACHE)
                    .build();
        }
        Response originalResponse = chain.proceed(request);
        if (Utils.isConnectByNet()) {
            //有网的时候读接口上的@Headers里的配置，你可以在这里进行统一的设置
            String cacheControl = request.cacheControl().toString();

            if (TextUtils.isEmpty(cacheControl)) {
                return originalResponse.newBuilder().
                        header("Cache-Control", cacheControl)
                        .removeHeader("Pragma")
                        .build();
            } else {
                return originalResponse.newBuilder()
                        .header("Cache-Control", "public, only-if-cached, max-stale=" + Constants.CACHE_STALE_LONG)
                        .removeHeader("Pragma")
                        .build();
            }
        }
        return null;
    }
}
